from selenium import webdriver
import pytest
import os
import sys
import json
from time import sleep
from Common.plugs.get_log import Log
from Common.plugs.get_config import r_config
from Common.plugs.basepage import BasePage
import time
from selenium.webdriver.common.by import By
from TestDatas.GobalDatas import gobal_datas as GD
from TestDatas.LoginDatas.login_datas import success_data as LD
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
if sys.platform == "win32":
    conf_dir = os.path.join(BASE_DIR, 'Common/config/config.ini').replace('/', '\\')
else:
    conf_dir = os.path.join(BASE_DIR, 'Common/config/config.ini')

driver_dir = r_config(conf_dir, "driver", "dirver_path")
cookie_dir = r_config(conf_dir, "cookie", "cookie_path")
log_dir = r_config(conf_dir, "log", "log_path")
logger = Log(log_dir)


class LoginLocator:
    username_loc = (By.XPATH, "//*[@placeholder='请输入手机号码']")
    password_loc = (By.XPATH, "//*[@placeholder='请输入密码']")
    click_login = """document.evaluate('//*[text()="登 录"]', document).iterateNext().click();"""
    switch_company = """document.evaluate('//*[text()="{CROP_NAME}"]/../../../../..//*[text()="探迹营销"]', document).iterateNext().click();""".format(CROP_NAME=GD.CROP_NAME)
    # error_msg_loc = (By.CLASS_NAME, 'el-message__content')


class LoginPage(BasePage):

    # 登录
    def login(self, username, password):
        loc = LoginLocator
        doc = '登录页面_登录功能'
        self.input_element(loc.username_loc, username, doc)
        self.input_element(loc.password_loc, password, doc)
        self.js_execute_script(loc.click_login, doc)
        time.sleep(2)
        self.js_execute_script(loc.switch_company)
        time.sleep(1)

    # 获取错误提示
    def get_login_errMsg(self):
        loc = LoginLocator
        doc = '登录页面_登录功能错误信息_获取错误信息'
        # self.wait_eleVisible(loc.error_msg_loc)
        return self.get_element_text(loc.error_msg_loc, doc)


def get_cookie():
    try:
        sess = requests.session()
        with open(cookie_dir, "r") as fp:
            cookie = fp.read()
        headers = {'Host': 'market-test.tangees.com', 'Connection': 'keep-alive', 'Content-Length': '74',
                   'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="90", "Microsoft Edge";v="90"', 'Accept': 'application/json',
                   'sec-ch-ua-mobile': '?0',
                   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 Edg/90.0.818.62',
                   'Content-Type': 'application/json;charset=UTF-8', 'Origin': 'https://market-test.tangees.com', 'Sec-Fetch-Site': 'same-origin',
                   'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty',
                   'Referer': 'https://market-test.tangees.com/customer-drainage/personal-code/employee', 'Accept-Encoding': 'gzip, deflate, br',
                   'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                   'Cookie': '{0}'.format(cookie)}
        url = GD.GET_COOKIE_URL
        sess.headers = headers
        params = None
        jsondata = {'current': 1, 'pageSize': 10, 'pageNum': 1, 'order': [1], 'sort': ['update_time']}

        postdata = None

        resp = sess.post(url, verify=False, json=jsondata, data=postdata, params=params)
        r = json.loads(resp.text)
        if r['errCode'] == 0:
            logger.info("==========使用本地COOKIE===========")
            return cookie
        else:
            raise ValueError("cookie过期")
    except:
        logger.info("==========重新获取COOKIE===========")
        global driver
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--headless')  # # 浏览器不提供可视化页面
        chrome_options.add_argument('--disable-gpu')  # 禁用GPU加速,GPU加速可能会导致Chrome出现黑屏，且CPU占用率高达80%以上
        driver = webdriver.Chrome(executable_path=driver_dir, options=chrome_options)
        driver.implicitly_wait(5)
        driver.maximize_window()
        driver.get(GD.LOGIN)
        LoginPage(driver).login(LD['PHONE'], LD['PASSWORD'])
        sleep(2)
        cookies = driver.get_cookies()[0]
        cookie = '{name}={value}'.format(name=cookies['name'], value=cookies['value'])
        with open(cookie_dir, "w") as fp:
            fp.writelines(cookie)
        driver.quit()
        return cookie


@pytest.fixture(scope='session')
def get_time(name):
    time = '20210818' + name
    return time


@pytest.fixture(scope='session')
def project_session_start():
    logger.info("==========开始 XX项目 执行测试===========")
    logger.info("==========获取cookie===========")
    yield get_cookie()
    logger.info("==========结束 XX项目 测试===========")


@pytest.fixture(scope='module')
def project_module_start():
    logger.info("==========开始 XX模块 执行测试===========")
    logger.info("==========获取cookie===========")
    yield get_cookie()
    logger.info("==========结束 XX模块 测试===========")

# @pytest.hookimpl(tryfirst=True, hookwrapper=True)
# def pytest_runtest_makereport(item, call):
#     '''
#     获取每个用例状态的钩子函数
#     :param item:
#     :param call:
#     :return:
#     '''
#     # 获取钩子方法的调用结果
#     outcome = yield
#     rep = outcome.get_result()
#     # 仅仅获取用例call 执行结果是失败的情况, 不包含 setup/teardown
#     if rep.when == "call" and rep.failed:
#         logger.info(rep)
#     if rep.when == "call" and rep.passed:
#         logger.info(rep)
